import os
import logging
import logging.handlers

import wx
from wx.lib.pubsub import Publisher as pub

def image_from_file(path, size=(144,90)):
    "Opens the image, given the full path, and returns it."
    if path != '':
        image = wx.Image(path)
    else:
        file_path = os.path.split(__file__)[0]
        not_in_database_path = os.path.join(file_path, "not_in_database.png") 
        image = wx.Image(not_in_database_path)
    image.Rescale(size[0],size[1])
    image = image.ConvertToBitmap()
    return image


def list_to_lines(list_of_strings, max=None):
    """Given a list of strings, it returns a single 
        string with newlines between strings."""
    if max is None:
        hi = len(list_of_strings)-1
    else:
        hi = min(max,len(list_of_strings)-1)

    string = ''
    for line in list_of_strings[:hi]:
        string += line + '\n'
    if max and max <= hi:
        string += '...\n'
    return string


def setup_logger(log_filename=os.path.join("view_data",
                                           "logfiles",
                                           "view_data.log"), 
                 main_logger_name='View_data'):
    """Uses the python standard library's logging module to set up a logger
        with a rotating file handler and a handler that spits info to the
        screen."""
    # Set up a specific logger with our desired output level
    main_logger = logging.getLogger(main_logger_name)
    main_logger.setLevel(logging.DEBUG)

    # Add the log message handler to the logger
    handler = logging.handlers.RotatingFileHandler(
                  log_filename, maxBytes=1000000, backupCount=5)

    # create formatter
    formatter = logging.Formatter(
                    "%(levelname)s|%(asctime)s[%(name)s]: %(message)s")
    handler.setFormatter(formatter)

    main_logger.addHandler(handler)

    # create console handler and set level to debug
    spit = logging.StreamHandler()
    spit.setLevel(logging.DEBUG)
    # create formatter
    spit_formatter = logging.Formatter("%(levelname)s[%(name)s]: %(message)s")
    # add formatter to ch
    spit.setFormatter(spit_formatter)
    # add ch to logger
    main_logger.addHandler(spit)


class ShoppingCart():
    '''
    This object class represents a shopping cart system for data.  
    You can put things into it and take things out of it.
    '''
    def __init__(self):
        self.items  = []
        self.removed_items = []

    def add(self, item):
        '''
        If item is not already in cart, add it.
        '''
        if item not in self.items:
            self.items.append(item)
            try: self.removed_items.remove(item)
            except ValueError: pass
            pub.sendMessage("ITEM ADDED TO CART", item)

    def remove(self, item):
        '''
        If item is in cart, remove it.
        '''
        try:
            self.items.remove(item)
            self.removed_items.append(item)
            pub.sendMessage("ITEM REMOVED FROM CART", item)
        except ValueError:
            pass

    def add_or_remove(self, item):
        '''
        If item is in cart remove it, otherwise add it 
        '''
        if item in self.items:
            self.remove(item)
        else:
            self.add(item)
